import $ from 'jquery';
import {message} from 'antd';
import {observable, action} from 'mobx';

class UserStore {
  @observable user;

  constructor() {
    try {
      let user = JSON.parse(localStorage.getItem('user'));
      this.user = user;
    } catch (e) {
      console.log(e)
    }
  }

  register(user) {
    return $.ajax({
      type: 'POST',
      url: '/api/register',
      data: JSON.stringify(user)
    });
  }

  @action
  logout() {
    this.user = null;
    localStorage.removeItem('user');
  }

  @action
  login(user) {
    let self = this;

    return $.ajax({
      type: 'POST',
      url: '/api/login',
      data: JSON.stringify(user)
    }).then((payload) => {
      if (payload.status === 'success') {
        self.user = user;
        localStorage.setItem('user', JSON.stringify(user));
      }
      return payload;
    });
  }
}

export default new UserStore()
